#!/usr/bin/env bash

# Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

srcdir=${pkg}
cd ${srcdir} || exit 1

# dont use toolchain file
rm rust-toolchain

# time 0.3.21 not compatible with rust 1.80
sed -i 's/time = { version = "0.3"/time = { version = ">=0.3.35"/g' Cargo.toml

cargo fetch || exit 1

if [ "${triple_env}" == "ohos" ]; then
    # fix nix<0.29
    # FIXME: better way to do this?
    for i in /.cargo/registry/src/*/nix-*/src/; do
        has_ohos=$(cat $i/sys/statfs.rs | grep "target_env = \"ohos\"")
        if [ $? -ne 0 ]; then
            nix_version=${i##}
            find $i -name '*.rs' -exec sed -i 's/target_env = \"musl\"/target_env = \"ohos\"/g' {} \;
        fi

        # mqueue and aio are not supported in ohos 4.1
        sed -i 's/pub mod mqueue;/\/\/pub mod mqueue;/g' $i/lib.rs
        sed -i 's/pub mod aio;/\/\/pub mod aio;/g' $i/sys/mod.rs

        # shm are not supported in ohos 4.1
        sed -i 's/target_os = \"android\"/target_env = \"ohos\"/g' $i/sys/mman.rs
    done

    # FIXME: better way to do this?
    for i in /.cargo/registry/src/*/socket2-*/src/; do
        sed -i 's/target_env = \"musl\"/target_env = \"ohos\"/g' $i/sys/unix.rs
    done

    # shm are not supported in ohos 4.1
    for i in /.cargo/registry/src/*/wayland-cursor-0.31.0/src/; do
        cat >$i/lib.rs.patch << EOM
--- lib.rs.~1~	2025-07-18 21:36:59.169594783 +0800
+++ lib.rs	2025-07-18 21:38:16.677671131 +0800
@@ -57,7 +57,7 @@
 use nix::fcntl;
 use nix::sys::{mman, stat};
 use nix::unistd;
-#[cfg(any(target_os = "linux", target_os = "android"))]
+#[cfg(any(target_os = "linux", target_os = "android", target_env = "ohos"))]
 use {nix::sys::memfd, std::ffi::CStr};
 
 use wayland_client::backend::{InvalidId, ObjectData, WeakBackend};
@@ -376,7 +376,7 @@
 /// Create a shared file descriptor in memory.
 fn create_shm_fd() -> IoResult<RawFd> {
     // Only try memfd on systems that provide it, (like Linux, Android)
-    #[cfg(any(target_os = "linux", target_os = "android"))]
+    #[cfg(any(target_os = "linux", target_os = "android", target_env = "ohos"))]
     loop {
         match memfd::memfd_create(
             CStr::from_bytes_with_nul(b"wayland-cursor-rs\0").unwrap(),
@@ -384,17 +384,21 @@
         ) {
             Ok(fd) => return Ok(fd),
             Err(Errno::EINTR) => continue,
+            #[cfg(not(target_env = "ohos"))]
             Err(Errno::ENOSYS) => break,
             Err(errno) => return Err(errno.into()),
         }
     }
 
     // Fallback to using shm_open.
+    #[cfg(not(target_env = "ohos"))]
     let sys_time = SystemTime::now();
+    #[cfg(not(target_env = "ohos"))]
     let mut mem_file_handle = format!(
         "/wayland-cursor-rs-{}",
         sys_time.duration_since(UNIX_EPOCH).unwrap().subsec_nanos()
     );
+    #[cfg(not(target_env = "ohos"))]
     loop {
         match mman::shm_open(
             mem_file_handle.as_str(),
EOM

        patch -d $i -p0 < $i/lib.rs.patch || exit 1
    done
fi

cargo build \
    --release \
    --target ${triple_normalized} \
    -p rerun-cli \
    --no-default-features --features native_viewer \
    -j ${MAX_JOBS} \
    || exit 1

cargo build \
    --release \
    --target ${triple_normalized} \
    -p rerun_c \
    -j ${MAX_JOBS} \
    || exit 1
